import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:flutter_base/statemanagement_demo/components/goods_item.dart';
import 'package:flutter_base/statemanagement_demo/states/cart_model.dart';
import 'package:flutter_base/statemanagement_demo/models/goods_entity.dart';

class GoodsListPage extends StatelessWidget {
  const GoodsListPage({super.key});

  @override
  Widget build(BuildContext context) {
    List<GoodsEntity> goodsEntities = GoodsEntity.getMockGoodsEntities();

    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          onPressed: () => Navigator.of(context).pop(),
          icon: const Icon(Icons.arrow_back_ios),
        ),
        title: const Text('商品列表'),
        actions: <Widget>[
          IconButton(
            onPressed: () {
              Navigator.of(context).pushNamed('my_cart_page');
            },
            icon: const Icon(Icons.shopping_cart),
          ),
        ],
      ),
      body: Consumer<CartModel>(
        builder: (context, value, child) {
          return ListView.builder(
            itemBuilder: (context, index) {
              GoodsEntity goodsEntity = goodsEntities[index];
              bool isInCart = context.read<CartModel>().isInCart(goodsEntity);
              return Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Expanded(child: GoodsItem(goodsEntity)),
                  TextButton(
                    onPressed: isInCart
                        ? null
                        : () {
                            // var cart = context.read<CartModel>();
                            // cart.add(goodsEntity);
                            value.add(goodsEntity);
                          },
                    child: isInCart
                        ? const Icon(Icons.check, semanticLabel: 'ADDED')
                        : const Text('ADD'),
                  ),
                ],
              );
            },
          );
        },
      ),
    );
  }
}
